#include "PostscriptDoc.h"
#include <sstream>

PostscriptDoc::PostscriptDoc()
: mMeta()
, mProlog()
{
}

PostscriptDoc::~PostscriptDoc()
{
}

void PostscriptDoc::load(std::istream &is)
{
	int lineNo = 0;
	
	while(!is.eof()) {
		std::streampos pos = is.tellg();
		std::string line;
		
		getline(is, line);
		
		if (lineNo == 0) {
			if (line.find("!PS-Adobe-") == std::string::npos)
				CXXTHROW;
		}
		lineNo++;
		
		if (line.find("%%") == 0) {
			std::string dummy;
			if (line.find("%%LanguageLevel: ") == 0) {
				std::istringstream iss(line);
				iss >> dummy >> mMeta.mLanguageLevel;
			}
			if (line.find("%%DocumentMedia: ") == 0) {
				std::istringstream iss(line);
				iss >> dummy >> mMeta.mMedia >> mMeta.mWidth >> mMeta.mHeight;
			}
			if (line.find("%%BeginProlog") == 0) {
				mProlog.mStartLineNo = lineNo;
				mProlog.mStartPos = pos;
			}
			if (line.find("%%EndProlog") == 0) {
				mProlog.mEndLineNo = lineNo;
				mProlog.mEndPos = pos;
			}
			if (line.find("%%Page:") == 0) {
				if (mPages.size() != 0) {
					//not the first page
					Page &last = mPages.back();
					last.mEndLineNo = lineNo - 1;
					last.mEndPos = pos;
				}
				
				Page page;
				page.mStartLineNo = lineNo;
				page.mStartPos = pos;
				mPages.push_back(page);
			}
			if (line.find("%%PageOrientation: ") == 0 && mPages.size()) {
				std::istringstream iss(line);
				Page &last = mPages.back();
				iss >> dummy >> last.mOrientation;
			}
			if (line.find("%%PageMedia: ") == 0 && mPages.size()) {
				std::istringstream iss(line);
				Page &last = mPages.back();
				iss >> dummy >> last.mMedia;
			}
			if (line.find("%%PageBoundingBox: ") == 0 && mPages.size()) {
				std::istringstream iss(line);
				Page &last = mPages.back();
				iss >> dummy >> last.mLeft >> last.mTop >> last.mWidth >> last.mHeight;
			}
			if (line.find("%%Trailer") == 0) {
				Page &last = mPages.back();
				last.mEndLineNo = lineNo - 1;
				last.mEndPos = pos;
			}
		}
	}	
}
